#!/bin/bash -e

USER="zg"
PWD="zg2020"
HOST="192.168.60.200"
DEADLINE=""

usage() {
    echo "usage: $0 -u user -H host -p password -d deadline -h help"
    echo "        host: remote host ip default [192.168.60.200]"
    echo "        user: mysql user default [zg]"
    echo "        password: mysql password default [zg2020]"
    echo "        deadline: subscription's expire time greater then the deadline, like 2022-11-03 02:32:36"
    echo "        like ./dump_order.sh -umulong -pmulong2020 -H\"192.168.254.45\" -d\"`date +'%Y-%m-%d %H:%M:%S'`\""
    echo ""
}

while getopts "u:H:p:d:h" option; do
  case "$option" in
    u)
      USER=$OPTARG
      ;;
    p)
      PWD=$OPTARG
      ;;
    H)
      HOST=$OPTARG
      ;;
    d)
      DEADLINE=$OPTARG
      ;;
    h)
      usage
      exit 0
      ;;
    :|\?)
      usage
      exit 1
      ;;
  esac
done
if [ "$DEADLINE" == "" ]; then
  echo "ERROR: deadline must be input"
  usage
  exit 1
fi

sql_all="select order_id,substring_index(order_id, '..',1) src_order_id,receipt_data from db_payhistory.history_receipts
where is_subscription = 1 and pay_channel = 'gp' and status = 0 and expire_time > '"$DEADLINE"' order by add_time  desc"
sql="select receipt_data from db_payhistory.history_receipts where status = 0 and order_id = "

result_file="subscription_"`echo "$DEADLINE"|awk -F" " '{print $1}'`
if [ -f  "$result_file" ]; then
  rm $result_file
fi

mysql -u $USER -h $HOST -p$PWD -e "$sql_all" -N | while read line; do
{
  columns=($line)
  if [ ${columns[0]} != ${columns[1]} ]; then
    receipt_data=$(mysql -u $USER -h $HOST -p$PWD -r -Ne "$sql'"${columns[1]}"'")
    if [ -z "$receipt_data" ]; then
      echo "get order" ${columns[0]}  ${columns[1]}$ "receipt data error!!!!"
      exit -1
    fi
    echo ${columns[@]:0:2} $receipt_data >> $result_file
  else
    echo ${columns[@]} >> $result_file
  fi
}
done